package cz.data.common.rabbitmq.config;

import cz.data.common.support.YamlPropertySourceFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@EnableRabbit
@Configuration
@AutoConfigureAfter(RabbitAutoConfiguration.class)
@PropertySource(value = "classpath:rabbit-setting.yml", factory = YamlPropertySourceFactory.class, encoding = "UTF-8")
@EnableConfigurationProperties({RabbitProperties.class})
public class RabbitConfiguration {

    /**
     * 路由变更通知gateway-admin主题队列
     * @return 消息队列
     */
    @Bean
    public Queue gatewayAdminRouteQueue() {
        return new Queue(RabbitConstant.TOPIC_GATEWAY_ADMIN_ROUTE);
    }

    /**
     * 通用主题交换机
     * @return 主题交换机
     */
    @Bean
    public TopicExchange gatewayExchange() {
        return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE);
    }

    /**
     * 路由变更通知gateway-admin主题队列 绑定到 通用主题交换机
     * @return 绑定交换机和队列
     */
    @Bean
    public Binding gatewayAdminRouteQueueBinding() {
        Queue routeQueue = gatewayAdminRouteQueue();
        return BindingBuilder.bind(routeQueue).to(gatewayExchange()).with(routeQueue.getName());
    }

    /**
     * gateway-admin推送路由到gateway服务的交换机(广播)
     * @return 广播交换机
     */
    @Bean
    public FanoutExchange routeFanoutExchange() {
        return new FanoutExchange(RabbitConstant.ROUTE_FANOUT_EXCHANGE);
    }

    /**
     * 数据集市api发布与撤销的交换机()
     * @return 广播交换机
     */
    public FanoutExchange apiFanoutExchange() {
        return new FanoutExchange(RabbitConstant.API_FANOUT_EXCHANGE);
    }

    /**
     * 数据源变更通知交换机
     * @return 广播交换机
     */
    public FanoutExchange datasourceChangeFanoutExchange() {
        return new FanoutExchange(RabbitConstant.DSC_FANOUT_EXCHANGE);
    }
}
